package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class Client {
    private Socket socket;
    public Client(){
        try {
            /**
             * 实例化Socket就说与远端计算机建立连接的过程
             */
            System.out.println("正在连接服务器。。。");
            socket = new Socket("localhost",8090);
            System.out.println("与服务端建立连接！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void start(){
        try {
            //启动用来读取服务端消息的线程
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.setDaemon(true);//守护线程，我们不给服务端发消息了，该线程也就跟着结束
            t.start();

            OutputStream ots = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(ots);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);

            Scanner scanner = new Scanner(System.in);
            String line;
            while (true) {
                line = scanner.nextLine();{
                if ("exit".equalsIgnoreCase(line))
                    break;
                }
                pw.println(line);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                //关闭socket时与服务端进行挥手操作
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
    /**
     * 该线程负责读取服务端发过来的消息
     */
    private class ServerHandler implements Runnable{
        public void  run(){
            try {
                //通过socket获取输入流读取服务端发过来的消息
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String message;
                while ((message = br.readLine()) != null){
                    System.out.println(message);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
